package cn.huobi.pet.service.impl;

import cn.huobi.pet.domain.PetType;
import cn.huobi.pet.mapper.PetTypeMapper;
import cn.huobi.pet.service.IPetTypeService;
import cn.huobi.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author huobi
 * @since 2022-10-28
 */
@Service
public class PetTypeServiceImpl extends BaseServiceImpl<PetType> implements IPetTypeService {

    @Autowired
    private PetTypeMapper petTypeMapper;

    @Override
    public List<PetType> petTypeTree() {
        List<PetType> result = new ArrayList<>();
        // 查询全部动物类型
        List<PetType> petTypes = petTypeMapper.findAll();
        // 判断是否为空
        if (CollectionUtils.isEmpty(petTypes)){
            return result;
        }
        Map<Long, PetType> typeMap = petTypes.stream().collect(Collectors.toMap(PetType::getId, e -> e));
        for (PetType petType : petTypes) {
            if (petType.getPid() == null){
                result.add(petType);
            }else {
                PetType parent = typeMap.get(petType.getPid());
                if (parent == null){
                    break;
                }
                List<PetType> children = parent.getChildren();
                children.add(petType);
            }
        }
        return result;
    }
}
